import React, { useEffect, useState,} from 'react'
import { List, Avatar, Image, message, Button,  Space, Drawer, Cascader, Popconfirm,Row,Col} from 'antd';
import {HeartTwoTone} from '@ant-design/icons';
import axios from 'axios';
import GoodsCascader from '../../../../components/GoodsCascader'
import moment from 'moment'
import { useNavigate } from 'react-router-dom'
import myprovinceData from '../../../../js/provinceData';
export default function Index() {
  const loginUser = JSON.parse(localStorage.getItem("loginUser"));
  let changeapply = {}
  const navigate = useNavigate()
  const [listData, setListData] = useState([]);
  const [listDataBac, setListDataBac] = useState([]); //存一份获取的数据用于筛选
  const [mylistData, setmyListData] = useState([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [respondentchangeinfoid, setRespondentchangeinfoid] = useState(false);


  useEffect(() => {
    axios.get("http://localhost:8080/qryMyLike?id=" + loginUser.id).then(resp => {
        console.log(resp);
        setListData(resp.data.data);
        setListDataBac(resp.data.data)
      
    })
    return () => {
    };
  }, []);

  const openDrawer = (id) => {
    //id =>被申请交换的chaninfo id
    console.log('被申请交换的chaninfo id是:', id)
    setRespondentchangeinfoid(id)
    axios.get("http://localhost:8080/qryMyChange?id=" + loginUser.id).then(resp => {
      if (resp.data.state === "0") {
        setmyListData(resp.data.data);
      }
    })
    setDrawerVisible(true)

  }
  const drawerClose = () => {
    setDrawerVisible(false)
  }
  const makeApplyChange = (id) => {
    console.log('选择的我的交换id是:', id)
    changeapply.applychangeinfoid = id; //交换发起changoinfo id
    changeapply.applyerid = loginUser.id;
    changeapply.respondentchangeinfoid = respondentchangeinfoid
    axios.post("http://localhost:8080/makeApplyChange", changeapply).then(resp => {
      if (resp.data.state === "0") {
        message.success("请求成功,等待对方回应!", 1);
        setTimeout(() => {
          window.location.reload();
        }, 800);
      } else {
        message.error("操作失败!", 1)
        setTimeout(() => {
          window.location.reload();
        }, 800);
      }
    }).catch(err => {
      message.success("请求成功,等待对方回应!", 1);
      setTimeout(() => {
        window.location.reload();
      }, 800);
    })
  }
  const filterByGoods = (value) => {
    console.log(value);
    if (value) { //如果筛选了 执行
      console.log("baclistdata", listDataBac);
      setListData(listDataBac)
      let rs = "";
      for (let i = 0; i < value.length; i++) {
        rs += value[i];
      }
      console.log("筛选物品:", value);
      console.log("最终筛选物品str", rs);
      const newListData = listDataBac.filter(item => item.mytype === rs)
      console.log("物品类别筛选后的结果:", newListData);
      setListData(newListData)
    } else { //点击X后就是undefined把备份的listdata赋回去
      setListData(listDataBac)
    }

  }
  const filterCity = (value) => {
    console.log(value);
    if (value) { //如果筛选了 执行
      console.log("baclistdata", listDataBac);
      setListData(listDataBac)
      let rs = "";
      for (let i = 0; i < value.length; i++) {
        rs += value[i];
      }
      console.log("筛选物品:", value);
      console.log("最终筛选物品str", rs);
      const newListData = listDataBac.filter(item => item.city === rs)
      console.log("物品类别筛选后的结果:", newListData);
      setListData(newListData)
    } else { //点击X后就是undefined把备份的listdata赋回去
      setListData(listDataBac)
    }
  }

  const cancelLike=(item)=>{
    console.log(item);
    let params = {}
    params.userid = loginUser.id
    params.changeinfoid = item.id
    params.like = 0
    axios.post("http://localhost:8080/saveLike",params).then(
      setTimeout(() => {
          navigate('/userMenu')
        window.location.reload()
      }, 100)
    )
    
  }
  return (
    <div className="animate__animated animate__fadeIn">
      <Row justify="start">
        <Col xs={12} sm={10} md={8} xl={3}> <GoodsCascader style={{ width: '1REM', }} onChange={filterByGoods} title="物品类别" /></Col>
        <Col xs={12} sm={10} md={8} xl={3}> <Cascader style={{ width: '1REM', }} placeholder={"城市"} onChange={filterCity} options={myprovinceData} defaultValue={''} /></Col>
       
      </Row>
      <List
        itemLayout="vertical"
        size="large"
        pagination={{
          onChange: page => {
            console.log(page);
          },
          pageSize: 3,
        }}
        dataSource={listData}

        renderItem={item => (
          <List.Item
            key={item.id}
            actions={[
                
              <Button type="primary" disabled={item.complete}  onClick={() => { openDrawer(item.id) }}> {item.complete ==0?"申请交换":"物品已失效"}</Button>,
              <Popconfirm
              title={"取消收藏?"}
              onConfirm={() => {cancelLike(item)}}
              okText="是"
              cancelText="否"
            >
             <Space style={{cursor:'pointer'}}><HeartTwoTone twoToneColor="#eb2f96" />取消收藏</Space>
            </Popconfirm>
            ]}
            extra={
              <Image
                width={135}
                height={135}
                src={`http://localhost:8080/getChangeInfoPhoto?id=${item.id}`}
                fallback=""
              />
            }
          >
            <List.Item.Meta
                 avatar={<Avatar src={`http://localhost:8080/getUserHead?id=${item.createrid}`} />}//头像
                 title={`${item.title}`}
                 description={moment(Number(item.createtime)).format('YYYY-MM-DD HH:mm:ss')}
            />
            {item.message}

          </List.Item>
        )}

      />


      <Drawer
        title="选择你的物品用以交换"
        placement='bottom'
        width={500}
        onClose={drawerClose}
        height={'80%'}
        visible={drawerVisible}
      >
        <List
          itemLayout="vertical"
          size="large"
          pagination={{
            pageSize: 3,
          }}
          dataSource={mylistData}

          renderItem={item => (
            <List.Item
              key={item.id}
              extra={
                <Image
                  width={135}
                  height={135}
                  src={`http://localhost:8080/getChangeInfoPhoto?id=${item.id}`}
                />
              }
            >
              <List.Item.Meta
                avatar={<Avatar src={`http://localhost:8080/getUserHead?id=${item.createrid}`} />}
                title={loginUser.nickname}
                description={`标题:${item.title}`}
              />
              {item.message} <br />
              <Button type='primary' style={{ marginTop: 20 }} onClick={() => { makeApplyChange(item.id) }}>选择</Button>

            </List.Item>
          )}

        />
      </Drawer>
    </div>
  )
}
